package com.example.myproject.service.impl;

import com.example.myproject.dto.comment.CommentRequest;
import com.example.myproject.dto.comment.CommentResponse;
import com.example.myproject.dto.comment.CommentsListResponse;
import com.example.myproject.mapper.CommentLikeMapper;
import com.example.myproject.mapper.CommentMapper;
import com.example.myproject.model.Comment;
import com.example.myproject.security.JwtAuthenticationFilter;
import com.example.myproject.service.CommentService;
import com.example.myproject.service.UserService;
import com.example.myproject.vo.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {
    
    @Autowired
    private CommentMapper commentMapper;
    
    @Autowired
    private CommentLikeMapper commentLikeMapper;
    
    @Autowired
    private UserService userService;
    
    @Override

    public CommentResponse postComment(CommentRequest req) {
        // 1. 创建评论实体
        Comment comment = new Comment();
        comment.setTorrentId(req.getTorrent_id());
        comment.setParentId(req.getParent_id());
        comment.setContent(req.getComment_content());


        // 获取当前用户ID - 修改这里
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Long userId = ((JwtAuthenticationFilter.UserPrincipal) auth.getPrincipal()).getId();
        comment.setUserId(userId);

        // 2. 格式化内容
        comment.setFormattedContent(formatContent(req.getComment_content()));
        comment.setCreateTime(LocalDateTime.now());
        comment.setLikesCount(0);

        // 3. 保存到数据库
        commentMapper.insert(comment);

        // 4. 构建响应
        CommentResponse response = new CommentResponse();
        response.setComment_id(comment.getCommentId());
        response.setTorrent_id(comment.getTorrentId());
        response.setUser_id(comment.getUserId().intValue());
        response.setParent_id(comment.getParentId());
        response.setComment_content(comment.getContent());
        response.setFormatted_content(comment.getFormattedContent());
        response.setComment_createtime(comment.getCreateTime().toString());

        // 5. 处理@用户
        List<CommentResponse.MentionedUser> mentionedUsers = new ArrayList<>();
        if (req.getMentioned_users() != null) {
            for (Integer mentionedUserId : req.getMentioned_users()) {
                UserInfoVO userInfo = userService.getUserInfo(mentionedUserId.longValue());

                if (userInfo != null) {
                    CommentResponse.MentionedUser mu = new CommentResponse.MentionedUser();
                    mu.setUser_id(mentionedUserId);
                    mu.setUsername(userInfo.getUserName());
                    mentionedUsers.add(mu);
                }
            }
        }
        response.setMentioned_users(mentionedUsers);

        return response;
    }
    
    @Override
    public CommentsListResponse getComments(Integer torrentId, String sort, Integer page, Integer perPage) {
        // 获取当前用户ID
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
// 替换原来的Long.parseLong(auth.getName())
        Long currentUserId = ((JwtAuthenticationFilter.UserPrincipal) auth.getPrincipal()).getId();
        // 计算分页
        int offset = (page - 1) * perPage;
        
        // 获取评论列表
        // 获取评论列表（只查 is_deleted=0）
        List<Comment> parentComments = commentMapper.findByTorrentIdAndNotDeleted(torrentId, sort, offset, perPage);
        Integer total = commentMapper.countByTorrentIdAndNotDeleted(torrentId);
        
        // 构建响应
        List<CommentsListResponse.CommentItem> items = new ArrayList<>();
        for (Comment comment : parentComments) {
            items.add(buildCommentItem(comment, currentUserId));
        }
        
        CommentsListResponse response = new CommentsListResponse();
        response.setTotal(total);
        response.setComments(items);
        return response;
    }
    
    private CommentsListResponse.CommentItem buildCommentItem(Comment comment, Long currentUserId) {
        CommentsListResponse.CommentItem item = new CommentsListResponse.CommentItem();
        
        // 基本信息
        item.setComment_id(comment.getCommentId());
        item.setContent(comment.getContent());
        item.setFormatted_content(comment.getFormattedContent());
        item.setLikes_count(comment.getLikesCount());
        
        // 检查当前用户是否点赞
        item.setUser_liked(commentLikeMapper.existsByCommentIdAndUserId(Long.valueOf(comment.getCommentId()), currentUserId) > 0);
        
        item.setComment_createtime(comment.getCreateTime().toString());
        
        // 用户信息
        UserInfoVO userInfo = userService.getUserInfo(comment.getUserId());
        CommentsListResponse.UserInfo ui = new CommentsListResponse.UserInfo();
        ui.setUser_id(userInfo.getUserId().intValue());
        ui.setUsername(userInfo.getUserName());
        ui.setAvatar_url(userInfo.getAvatarUrl());
        ui.setLevel(1); // 默认等级为1
        item.setUser_info(ui);
        
        // 回复列表
        List<Comment> replies = commentMapper.findRepliesByParentId(comment.getCommentId());
        if (replies != null && !replies.isEmpty()) {
            List<CommentsListResponse.CommentItem> replyItems = new ArrayList<>();
            for (Comment reply : replies) {
                replyItems.add(buildCommentItem(reply, currentUserId));
            }
            item.setReplies(replyItems);
        }
        
        return item;
    }
    
    private String formatContent(String content) {
        if (content == null) return "";
        
        // Markdown格式
        String formatted = content
            .replaceAll("\\*\\*(.+?)\\*\\*", "<strong>$1</strong>")
            .replaceAll("!\\[(.*?)\\]\\((.*?)\\)", "<img src=\"$2\">");
            
        // @用户链接
        formatted = formatted.replaceAll("@(\\w+)", "<a href=\"/user/$1\">@$1</a>");
        
        return formatted;
    }
}